//
//  NSManagedObject+SetValueWithDictionary.m
//  WC
//
//  Created by 杨鑫 on 15/5/7.
//  Copyright (c) 2015年 智康. All rights reserved.
//

#import "NSManagedObject+SetValueWithDictionary.h"

@implementation NSManagedObject (SetValueWithDictionary)

- (void)safeSetValuesForKeysWithDictionary:(NSDictionary *)keyedValues
{
    
     NSMutableDictionary *attributes =[NSMutableDictionary new];
     [attributes addEntriesFromDictionary:[[self entity] attributesByName]];
   
//    [attributes addEntriesFromDictionary: [[self entity] relationshipsByName]];
    
    
    for (NSString *attribute in attributes) {
        id value = [keyedValues objectForKey:attribute];
        
        if ([attribute isEqualToString:@"stringId"]) {
            value = [keyedValues objectForKey:@"id"];
        }
        
//        if ([attribute isEqualToString:@"localUpdateTime"] && value == nil) {
//            value = [NSDate date];
//        }
        
        if (value == nil) {
            // Don't attempt to set nil, or you'll overwite values in self that aren't present in keyedValues
            continue;
        }
    
        if ([attribute isEqualToString:@"nursingOrderStatus"]){
            NSMutableData *data =[NSMutableData new];
            NSKeyedArchiver *archiver =[[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
            [archiver encodeObject:[keyedValues objectForKey:@"nursingOrderStatus"] forKey:@"nursingOrderStatus"];
            [archiver finishEncoding];
            value =data;
            
        }
        if ([attribute isEqualToString:@"serviceType"]){
            NSMutableData *data =[NSMutableData new];
            NSKeyedArchiver *archiver =[[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
            [archiver encodeObject:[keyedValues objectForKey:@"serviceType"] forKey:@"serviceType"];
            [archiver finishEncoding];
            value =data;
    
        }
       
        NSAttributeType attributeType = [[attributes objectForKey:attribute] attributeType];
        if ( attributeType == NSStringAttributeType && [value isKindOfClass:[NSNumber class]] ) {
            value = [value stringValue];
        } else if ( (attributeType == NSInteger16AttributeType || attributeType == NSInteger32AttributeType || attributeType == NSInteger64AttributeType) && [value isKindOfClass:[NSString class]] ) {
            value = [NSNumber numberWithInteger:[value integerValue]];
        } else if ( attributeType == NSBooleanAttributeType && [value isKindOfClass:[NSString class]] ) {
            if ([@"YES" isEqual:value]) {
                value = [NSNumber numberWithBool:YES];
            } else {
                value = [NSNumber numberWithBool:NO];
            }
        } else if ( attributeType == NSFloatAttributeType && [value isKindOfClass:[NSString class]] ) {
            value = [NSNumber numberWithDouble:[value doubleValue]];
        }
        
        [self setValue:value forKey:attribute];
    }
}

@end
